import { getClassCheckinHistory, getCheckinRecordList } from '../../api/api.js';

Page({
    data: {
        classId: '',
        className: '',
        checkinList: [],
        loading: true
    },

    onLoad(options) {
        const { classId, className } = options;
        this.setData({
            classId,
            className: className || '班级'
        });

        wx.setNavigationBarTitle({
            title: className ? `${className}的签到记录` : '签到历史'
        });

        this.loadCheckinHistory();
    },

    /**
     * 加载签到历史
     */
    loadCheckinHistory() {
        const { classId } = this.data;

        if (!classId) {
            this.setData({
                checkinList: [],
                loading: false
            });
            return;
        }

        wx.showLoading({
            title: '加载中...',
        });

        getClassCheckinHistory(classId).then(res => {
            // 处理数据，计算百分比和格式化时间
            const checkinList = res.data.map(item => {
                // 计算百分比
                const total = item.totalStudents || 1; // 防止除以零
                const presentPercent = (item.presentCount / total) * 100;
                const latePercent = (item.lateCount / total) * 100;
                const absentPercent = (item.absentCount / total) * 100;

                // 格式化时间
                const startTime = new Date(item.startTime);
                const endTime = new Date(item.endTime);
                const formattedStartTime = this.formatDate(startTime);
                const formattedEndTime = this.formatDate(endTime);
                // 计算签到时长
                const duration = endTime - startTime;
                const durationInMinutes = Math.round(duration / (1000 * 60));
                // 计算是否已结束
                const isEnded = endTime < new Date();

                return {
                    ...item,
                    presentPercent,
                    latePercent,
                    absentPercent,
                    formattedStartTime,
                    formattedEndTime,
                    isEnded,
                    durationInMinutes,
                };
            });

            this.setData({
                checkinList,
                loading: false
            });
            wx.hideLoading();
        }).catch(err => {
            console.error('获取签到历史失败:', err);
            wx.hideLoading();
            wx.showToast({
                title: '加载失败',
                icon: 'error'
            });
            this.setData({ loading: false });
        });
    },

    /**
     * 格式化日期
     */
    formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    /**
     * 查看签到详情
     */
    viewCheckinDetail(e) {
        console.log('查看签到详情 - 事件触发:', e);
        const checkinHistoryId = e.currentTarget.dataset.id;
        console.log('获取到签到历史ID:', checkinHistoryId);

        if (!checkinHistoryId) {
            console.error('签到历史ID为空');
            wx.showToast({
                title: '数据错误',
                icon: 'error'
            });
            return;
        }

        console.log('准备跳转到签到记录页面:', `/pages/checkinrecord/checkinrecord?checkinHistoryId=${checkinHistoryId}`);

        wx.navigateTo({
            url: `/pages/checkinrecord/checkinrecord?checkinHistoryId=${checkinHistoryId}`,
            success: function() {
                console.log('跳转成功');
            },
            fail: function(error) {
                console.error('跳转失败:', error);
                wx.showToast({
                    title: '跳转失败',
                    icon: 'error'
                });
            }
        });
    },

    /**
     * 返回上一页
     */
    navigateBack() {
        wx.navigateBack();
    },

    /**
     * 下拉刷新
     */
    onPullDownRefresh() {
        this.loadCheckinHistory();
        wx.stopPullDownRefresh();
    },

    // 开启视频签到
    startVideoCheckin: function(e) {
        const checkinId = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/video_checkin/video_checkin?id=${checkinId}`
        });
    }
});